﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace TeBigScreenWpf
{
    /// <summary>
    /// Interaction logic for QuickWindow.xaml
    /// </summary>
    public partial class QuickWindow : Window
    {
        private ContextMenu MyContextMenu => this.FindResource("cmWindow") as ContextMenu;

        public QuickWindow(Page page, string title, int screen = 0)
        {
            InitializeComponent();

            this.Title = title;

            this.PreviewMouseRightButtonUp += Window_PreviewMouseRightButtonUp;

            fmMain.Navigate(page);

            this.MoveToScreen(screen);
        }

        public void ShowFullScreen(int screen = 0)
        {
            this.Show();
            this.SetFullScreenOn(screen);
        }

        private void Window_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            void PrepareMenuItem()
            {
                if (LogicalTreeHelper.FindLogicalNode(MyContextMenu, "miFullscreen") is MenuItem menu)
                {
                    menu.Items.Clear();

                    for (int i = 0; i < this.GetScreensCount(); i++)
                    {
                        var item = new MenuItem()
                        {
                            Name = $"miFullscreenOn{i}",
                            Header = $"第{i + 1}屏",
                        };

                        int idxScreen = i;

                        item.Click += (o, ea) => this.SetFullScreenOn(idxScreen);

                        menu.Items.Add(item);
                    }
                }
            }

            PrepareMenuItem();

            ContextMenu cm = MyContextMenu;
            cm.PlacementTarget = sender as UIElement;
            cm.Tag = Mouse.GetPosition(this);
            cm.IsOpen = true;
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.InvokeAsync(() =>
            {
                if (e.Source is MenuItem mi)
                {
                    switch (mi.Name)
                    {
                        case "miRestore":
                            this.ResetFullScreenOn();

                            break;

                        case "miClose":
                            this.Close();
                            break;

                        default:
                            break;
                    }
                }
            });
        }
    }
}